package com.example.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.db.bean.User;
import com.example.db.utils.DbHelper;
import com.example.db.utils.TimeUtils;
import com.snappydb.SnappydbException;

import junit.framework.TestCase;

import net.tsz.afinal.FinalDb;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * Created by kkmike999 on 16/2/12.
 */
public class AFinalTest extends TestCase {

	public static final int    COUNT  = 10000;
	public static final String dbName = "finaldb_" + (int) (Math.random() * 100);

	FinalDb db;
	User[]        users   = UserHelper.createUserList(COUNT);
	List<Integer> uidList = UserHelper.getUidList(users);

	@Before
	public void setUp() {
		db = FinalDb.create(DbApp.getContext(), dbName);
	}

	@After
	public void tearDown() throws SnappydbException {
		db.dropDb();
	}

	@Test
	public void sqlInsertObj() {
		TimeUtils.begin();

		DbHelper.beginTransaction(db);

		for (User user : users) {
			db.save(user);
		}

		DbHelper.endTransaction(db);

		System.out.println("AFinalTest(" + users.length + "): insert Obj time = " + TimeUtils.time());
	}

	@Test
	public void delObj() {
		sqlInsertObj();

		String uidIn = " uid in" + uidList.toString().replace("[", "(").replace("]", ")");

		TimeUtils.begin();

		DbHelper.beginTransaction(db);

		db.deleteByWhere(User.class, uidIn);

		DbHelper.endTransaction(db);

		System.out.println("AFinalTest(" + users.length + "): del Obj time = " + TimeUtils.time());
	}

	@Test
	public void getObj() {
		sqlInsertObj();

		TimeUtils.begin();

		String uidIn = " uid in" + uidList.toString().replace("[", "(").replace("]", ")");

		List<User> list = db.findAllByWhere(User.class, uidIn);

		System.out.println("AFinalTest(" + users.length + "): get Obj time = " + TimeUtils.time());
	}

	/**
	 * 获取表行数
	 */
	private int count(String table) {
		SQLiteDatabase database = DbHelper.getDatabase(db);

		Cursor cursor = database.rawQuery("SELECT COUNT(1) FROM " + table, new String[0]);

		cursor.moveToNext();
		return cursor.getInt(0);
	}
}
